import * as shiftArrangeService from '@/services/shiftArrange';
import * as sendSmsService from '@/services/sendSms';
import { message } from 'antd';
import { DEFAULT_RESPONE_SUCCESS } from '@/constants';
import moment from 'moment';

export default {
  namespace: 'dutyShift',

  state: {
    current: 1,
    pageSize: 1,
    total: 4,
    data: [
    ],
    rowKey: 'id'
  },

  subscriptions: {

  },

  effects: {
    *queryData({ payload }, { call, put }) {
      const { callback, ...extra } = payload;

      const response = yield call(shiftArrangeService.queryData, { ...extra });

      if (response && response.status === DEFAULT_RESPONE_SUCCESS) {
        const { result = {} } = response;
        const list = {};

        Object.keys(result).forEach(date => {
          const array = result[date];
          const shifts = {};
          array.forEach(item => {
            const { shift_id = {}, shift_title = {}, shift_unit = {}, shift_user = {} } = item;
            const { id, shift_name, start_date, end_date } = shift_id;
            const { id: title_id, title_name } = shift_title;
            const { id: unit_id } = shift_unit;
            const { id: user_id, user = {} } = shift_user;
            const { name, mobile } = user;

            if (!shifts[id]) {
              shifts[id] = { shift_name, start_date, end_date, children: [] };
            }
            shifts[id].children.push({ user_id, name, mobile, unit_id, shift_id: id, title_id, title_name, date });
          });

          list[date] = { ...shifts };
        });

        if (typeof callback === 'function') {
          callback(list);
        }
      }
    },
    *queryDataNew({ payload }, { call, put }) {
      const { callback, ...extra } = payload;

      const response = yield call(shiftArrangeService.queryData, { ...extra });

      if (response && response.status === DEFAULT_RESPONE_SUCCESS) {
        const { result = {} } = response;
        // 新页面-数组
        const arrayList = [];

        Object.keys(result).sort((a,b)=>{
          return moment(a, 'YYYY-MM-DD').valueOf() - moment(b, 'YYYY-MM-DD').valueOf()
        }).forEach(date => {
          const array = result[date];
          let shifts = {};
          array.forEach(item => {
            const { shift_id = {}, shift_title = {}, shift_unit = {}, shift_user = {}, shift_date } = item;
            const { shift_name, start_date, end_date } = shift_id;
            const { title_type, title_name } = shift_title;
            const { type_name } = title_type;
            const { unit_name, unit_address, unit_phone, unit_fax } = shift_unit;
            const { user_duty, user = {} } = shift_user;
            const { name, mobile } = user;
            shifts = { shift_id: shift_id.id, shift_title: shift_title.id, shift_unit: shift_unit.id, unit_name, name, type_name, mobile, unit_address, shift_name: shift_name + "(" + start_date + " ~ " + end_date + ")", shift_date, unit_phone, unit_fax, title_name };
            arrayList.push(shifts)
          });
        });
        console.log("arrayList", arrayList);

        yield put({
          type: 'changeState',
          payload: {
            newDataArr: arrayList
          },
        });
      }
    },
    *queryDataByDay({ payload }, { call, put }) {
      const { callback, ...extra } = payload;

      const response = yield call(shiftArrangeService.queryData, { ...extra });
      if (response && response.status === DEFAULT_RESPONE_SUCCESS) {
        const { result = {} } = response;
        const list = {};

        Object.keys(result).forEach(date => {
          const array = result[date];
          const shifts = {};

          array.forEach(item => {
            const { shift_id = {}, shift_title = {}, shift_unit = {}, shift_user = {} } = item;
            const { id, shift_name, start_date, end_date } = shift_id;
            const { id: title_id, title_name } = shift_title;
            const { id: unit_id } = shift_unit;
            const { id: user_id, user = {} } = shift_user;
            const { name, mobile } = user;

            if (!shifts[id]) {
              shifts[id] = { shift_name, start_date, end_date, children: [] };
            }
            shifts[id].children.push({ user_id, name, mobile, unit_id, shift_id: id, title_id, title_name, date });
          });

          list[date] = { ...shifts };
        });

        if (typeof callback === 'function') {
          callback(list[extra.shift_date]);
        }
      }
    },
    *saveOrUpdateData({ payload }, { call, put }) {
      const { callback, cell, data } = payload;

      let response = {};
      if (!cell.shift_user) {
        response = yield call(shiftArrangeService.saveData, [{ ...cell, shift_user: data.id }]);
      } else {
        response = yield call(shiftArrangeService.updateData, [{ ...cell, shift_user: data.id }]);
      }
      if (response && response.status === DEFAULT_RESPONE_SUCCESS) {
        if (typeof callback === 'function') {
          callback();
        }
      }
    },
    *deleteData({ payload }, { call, put }) {
      const { callback, data } = payload;
      const option = {
        method: 'POST',
        body: Array.isArray(data) ? data : [data]
      };
      const response = yield call(shiftArrangeService.deleteData, option);
      if (response && response.status === DEFAULT_RESPONE_SUCCESS) {
        if (typeof callback === 'function') {
          callback();
        }
      }
    },
    *downloadTemplate({ payload }, { call, put }) {
      const { name } = payload;

      const response = yield call(shiftArrangeService.downloadTemplate);
      if (response) {
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(response, name);
        } else {
          const URL = window.URL || window.webkitURL;
          const downloadUrl = URL.createObjectURL(response);
          const a = document.createElement('a');

          if (typeof a.download === 'undefined') {
            window.location = downloadUrl;
          } else {
            a.download = name;
            a.href = downloadUrl;
            a.style.display = 'none';
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(downloadUrl);
            document.body.removeChild(a);
          }
        }
      } else {
        message.error('下载失败！');
      }
    },
    *uploadData({ payload }, { call, put }) {
      const { callback, unitId, file } = payload;

      const formData = new FormData();
      formData.append('file', file);

      const response = yield call(shiftArrangeService.uploadData, { unitId }, { method: 'POST', body: formData });
      if (response && response.status === DEFAULT_RESPONE_SUCCESS) {
        const { result = {} } = response;
        const { state, errorNum, error } = result;

        if (typeof callback === 'function') {
          callback(state, errorNum, error);
        }
      }
    },
    *deriveExcel({ payload }, { call, put }) {
      const { callback, name, ...extra } = payload;

      try {
        const response = yield call(shiftArrangeService.deriveExcel, { method: 'POST', body: extra });
        if (response) {
          if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(response, name);
          } else {
            const URL = window.URL || window.webkitURL;
            const downloadUrl = URL.createObjectURL(response);
            const a = document.createElement('a');

            if (typeof a.download === 'undefined') {
              window.location = downloadUrl;
            } else {
              a.download = name;
              a.href = downloadUrl;
              a.style.display = 'none';
              document.body.appendChild(a);
              a.click();
              window.URL.revokeObjectURL(downloadUrl);
              document.body.removeChild(a);
            }
          }
          if (typeof callback === 'function') {
            callback();
          }
        } else {
          message.error('下载失败！');
        }
      } catch (e) {
        console.error(e);
        message.error('下载失败！');
      }
    },
    *deriveWord({ payload }, { call, put }) {
      const { callback, name, ...extra } = payload;

      try {
        const response = yield call(shiftArrangeService.deriveWord, { method: 'POST', body: extra });
        if (response) {
          if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(response, name);
          } else {
            const URL = window.URL || window.webkitURL;
            const downloadUrl = URL.createObjectURL(response);
            const a = document.createElement('a');

            if (typeof a.download === 'undefined') {
              window.location = downloadUrl;
            } else {
              a.download = name;
              a.href = downloadUrl;
              a.style.display = 'none';
              document.body.appendChild(a);
              a.click();
              window.URL.revokeObjectURL(downloadUrl);
              document.body.removeChild(a);
            }
          }
          if (typeof callback === 'function') {
            callback();
          }
        } else {
          message.error('下载失败！');
        }
      } catch (e) {
        console.error(e);
        message.error('下载失败！');
      }
    },
    *downloadWord({ payload }, { call, put }) {
      const { callback, name, type, ...extra } = payload;

      try {
        const response = yield call(shiftArrangeService.downloadWord, { type }, { method: 'POST', body: extra.option });
        if (response) {
          if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(response, name);
          } else {
            const URL = window.URL || window.webkitURL;
            const downloadUrl = URL.createObjectURL(response);
            const a = document.createElement('a');

            if (typeof a.download === 'undefined') {
              window.location = downloadUrl;
            } else {
              a.download = name;
              a.href = downloadUrl;
              a.style.display = 'none';
              document.body.appendChild(a);
              a.click();
              window.URL.revokeObjectURL(downloadUrl);
              document.body.removeChild(a);
            }
          }
          if (typeof callback === 'function') {
            callback();
          }
        } else {
          message.error('下载失败！');
        }
      } catch (e) {
        console.error(e);
        message.error('下载失败！');
      }
    },
    *sendSms({ payload }, { call, put }) {
      const { data, callback } = payload;
      const option = {
        method: 'POST',
        body: data
      };

      const response = yield call(sendSmsService.saveData, option);
      if (response && response.status === DEFAULT_RESPONE_SUCCESS) {
        if (typeof callback === 'function') {
          callback();
        }
      }
    },
    *deleteSms({ payload }, { call, put }) {
      const { data, callback } = payload;
      const option = {
        method: 'POST',
      };

      const response = yield call(sendSmsService.updateData, data, option);
      if (response && response.status === DEFAULT_RESPONE_SUCCESS) {
        if (typeof callback === 'function') {
          callback();
        }
      }
    },
  },

  reducers: {
    clear(state, { payload }) {
      return {
        rowKey: 'id'
      };
    },
    changeState(state, { payload }) {
      return {
        ...state,
        ...payload
      };
    }
  },
};
